package com.siqi.hr.common.generator;

/**
 * 唯一id生成器(xiaogq)
 */
public abstract class IdGenerator {
	public String generatorSource() {
		int tableCode = getTableCode();
		long timeMills = System.currentTimeMillis();
		double ramdoCount = Math.random() * 90000.0D + 10000.0D;

		String source = new StringBuilder().append(parseCode(String.valueOf(tableCode).toCharArray(), 4)).append(timeMills).append(ramdoCount).toString();

		return source.substring(0, source.indexOf('.'));
	}

	public abstract int getTableCode();

	public static String generatIdStr(String source) {
		String per1 = source.substring(0, 7);
		String per2 = source.substring(7, 14);
		String per3 = source.substring(14, 21);
		return new StringBuilder().append(parseCode(CharTransformer.encode(Integer.parseInt(per1)), 4)).append(parseCode(CharTransformer.encode(Integer.parseInt(per2)), 4)).append(parseCode(CharTransformer.encode(Integer.parseInt(per3)), 4)).toString();
	    
	}

	public static String generatIdSource(String id) {
		String s1 = id.substring(0, 4);
		String s2 = id.substring(4, 8);
		String s3 = id.substring(8, 12);

		StringBuilder result = new StringBuilder().append(parseCode(String.valueOf(CharTransformer.encodeCount(s1)).toCharArray(), 7))
				.append(parseCode(String.valueOf(CharTransformer.encodeCount(s2)).toCharArray(), 7))
				.append(parseCode(String.valueOf(CharTransformer.encodeCount(s3)).toCharArray(), 7));

		return result.toString();
	}

	public static char[] parseCode(char[] praeChars, int length) {
		if (length - praeChars.length < 0)
			throw new IllegalArgumentException(String.valueOf(praeChars)+ "小于指定的长度" + length);
		if (length - praeChars.length > 0) {
			char[] pres = fillPreChar(length - praeChars.length, '0');
			return arrayAttach(pres, praeChars);
		}
		return praeChars;
	}

	public static char[] fillPreChar(int length, char c) {
		if (length < 1)
			throw new IllegalArgumentException("长度小于1");
		char[] source = new char[length];
		for (int i = 0; i < length; i++) {
			source[i] = c;
		}
		return source;
	}

	public static char[] arrayAttach(char[] t1, char[] t2) {
		int t1Length = t1.length;
		int t2Length = t2.length;
		int t3Length = t1Length + t2Length;
		if ((t1Length < 1) || (t2Length < 1))
			throw new IllegalArgumentException("参数长度小于1");
		char[] t3 = new char[t3Length];

		for (int i = 0; i < t3Length; i++) {
			if (i < t1Length)
				t3[i] = t1[i];
			else
				t3[i] = t2[(i - t1Length)];
		}
		return t3;
	}

	public String generator() {
		return generatIdStr(generatorSource());
	}

	/**
	 * 获取唯一id方法
	 * @param tableCode
	 * @return
     */
	public static String createId(final int tableCode){
		String id = new IdGenerator() {
			public int getTableCode() {
				return tableCode;
			}
		}.generator();
		return id;
	}
	
	public static void main(String [] args){
		String id = IdGenerator.createId(0);
		System.out.println("id===="+id);
	}
}